package com.sgb.kjwl.view.ui.activity.vehicleManagement;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityDriverLocationBinding;
import com.sgb.kjwl.model.entity.transport.VehicleDetail;
import com.sgb.kjwl.utils.DefaultUtil;
import com.swgk.core.util.UserOperating;
import com.sgb.kjwl.view.constant.RouterKey;
import com.swgk.core.dialog.RoundDialog;
import com.sgb.kjwl.viewmodel.transport.DriverLocationModel;

/**
 * Describe:
 * Author:  yangLei
 * Date:    2021/6/2
 */
public class DriverLocationActivity extends AppActivity implements AMap.OnMarkerClickListener {
    DriverLocationModel viewModel;
    private ActivityDriverLocationBinding binding;
    private AMap aMap;    //地图控制器
    private MapView mapView;    //高德3DMap  地图显示View

    //信息类
    private VehicleDetail mEntity;

    /**
     * 跳转司机位置
     */
    public static void start(@NonNull Context context, VehicleDetail entity) {
        Intent intent = new Intent(context, DriverLocationActivity.class);
        intent.putExtra(RouterKey.DATA, entity);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mapView != null) {
            mapView.onCreate(savedInstanceState);
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，
        //保存地图当前的状态
        if (mapView != null)
            mapView.onSaveInstanceState(outState);
    }

    @Override
    protected void init() {
        viewModel = new ViewModelProvider(this).get(DriverLocationModel.class);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_driver_location);
        binding.include.titleView.setText("司机位置");
        binding.include.ivBack.setOnClickListener(v -> finish());
        mapView = binding.mapView;
        aMap = mapView.getMap();
        initMap();
        mEntity = (VehicleDetail) getIntent().getSerializableExtra(RouterKey.DATA);
        syncLocation();
    }

    /**
     * 初始化地图（高德3D地图）
     */
    private void initMap() {
        if (aMap == null)
            aMap = mapView.getMap();
        /**
         * 设置一些amap的属性
         */
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));//缩放比例
        //地图文字的Z轴指数,设置为2可以将地图底图文字设置在添加的覆盖物之上
        aMap.setMapTextZIndex(2);
        UiSettings uiSettings = aMap.getUiSettings();//地图的UI设置控制器
        uiSettings.setCompassEnabled(false);// 设置指南针是否显示
        uiSettings.setZoomControlsEnabled(false);// 设置缩放按钮是否显示
        uiSettings.setScaleControlsEnabled(true);// 设置比例尺是否显示
        uiSettings.setRotateGesturesEnabled(true);// 设置地图旋转是否可用
        uiSettings.setTiltGesturesEnabled(true);// 设置地图倾斜是否可用
        uiSettings.setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.setOnMarkerClickListener(this);
    }

    /**
     * 同步司机位置
     */
    private void syncLocation() {
        if (mEntity == null) return;
        addMarker(new LatLng(mEntity.getLatitude(), mEntity.getLongitude()), R.mipmap.ic_driver_location_marker, mEntity);
        //移动到当前位置
        cameraToPosition(mEntity.getLatitude(), mEntity.getLongitude());
        //展示弹窗
        showDriverDialog();
    }

    /**
     * 添加覆盖物
     */
    private void addMarker(LatLng latLng, @DrawableRes int drawable, VehicleDetail entity) {
        MarkerOptions markerOption = new MarkerOptions();
        markerOption.position(latLng);
        markerOption.icon(BitmapDescriptorFactory.fromResource(drawable));
        Marker marker = aMap.addMarker(markerOption);
        //设置附着对象
        marker.setObject(entity);
    }


    /**
     * 根据经纬度移动地图，标记中心点
     */
    private void cameraToPosition(double lat, double lng) {
        if (lat == 0 || lng == 0) return;
        //切换地图中心点
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        if (mapView != null)
            mapView.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        if (mapView != null)
            mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        if (mapView != null)
            mapView.onPause();
    }

    @Override
    public boolean onMarkerClick(Marker marker) {
        //司机点击弹窗
        showDriverDialog();
        return false;
    }

    /**
     * 司机位置信息弹窗
     */
    private void showDriverDialog() {

        if (mEntity != null) {
            //司机信息
            binding.infoLayout.tvDriverLocationTitle.setText(String.format("%s %s",
                    mEntity.getCarNumber(),
                    mEntity.getName()));
//            binding.tvDriverLocationContent.setText(String.format("%s%s%s%s",
//                    mEntity.getProvinceName(),
//                    mEntity.getCityName(),
//                    mEntity.getDistrictName(),
//                    mEntity.getDetailAddress()));
            //2.0.2.1改为只取详细地址
            if (!TextUtils.isEmpty(mEntity.getDetailAddress())) {
                binding.infoLayout.tvDriverLocationContent.setText(DefaultUtil.getString(mEntity.getDetailAddress()));
            }
            if (mEntity.getUserVO() != null && TextUtils.isEmpty(mEntity.getUserVO().getImAccount())) {
                binding.infoLayout.tvDriverLocationIm.setAlpha(0.5f);
                binding.infoLayout.tvDriverLocationIm.setEnabled(false);
            } else {
                binding.infoLayout.tvDriverLocationIm.setAlpha(1f);
                binding.infoLayout.tvDriverLocationIm.setEnabled(true);
            }
            if (TextUtils.isEmpty(mEntity.getTelphone())) {
                binding.infoLayout.tvDriverLocationCall.setAlpha(0.5f);
                binding.infoLayout.tvDriverLocationCall.setEnabled(false);
            } else {
                binding.infoLayout.tvDriverLocationCall.setAlpha(1f);
                binding.infoLayout.tvDriverLocationCall.setEnabled(true);
            }
        }
        //设置监听
        binding.infoLayout.tvDriverLocationIm.setOnClickListener(this);
        binding.infoLayout.tvDriverLocationCall.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.tv_driver_location_im) {
            if (UserOperating.getInstance().isNotLogged(DriverLocationActivity.this)){
                return;
            }
            // TODO IM功能目前需要全部去掉，此处需要后期IM迁移完成后完善
            buildSingleTalking(mEntity.getUserVO().getImAccount());
        } else if (v.getId() == R.id.tv_driver_location_call) {
            //打电话
            if (UserOperating.getInstance().isNotLogged(DriverLocationActivity.this)){
                return;
            }
            showTelDialog(mEntity.getTelphone());
        }
    }



    private void showTelDialog(String phone) {
        new RoundDialog.Builder(this)
                .title("确认拨号")
                .content(phone)
                .confirm("拨打")
                .cancelable(false)
                .confirmCallback(v -> {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                })
                .show();
    }
}
